package com.woniuxy.springbootpro.interceptor;

import com.woniuxy.springbootpro.entity.Root;
import com.woniuxy.springbootpro.service.UserService;
import com.woniuxy.springbootpro.utile.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Order(2)
public class SecondInterceptor implements HandlerInterceptor {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器2收到请求:\t" + request.getRequestURI());

        Cookie cookie = CookieUtil.getCookie("token", request.getCookies());

        System.out.println("拦截器2:cookie" + cookie);

        List<Root> userRootList = userService.findUserPermission(Integer.parseInt(cookie.getValue()));
        System.out.println("userRootList:\t" + userRootList);

        String requestURI = request.getRequestURI();
        System.out.println("requestURI" + requestURI);

        boolean isHave = false;
        if(userRootList != null){
            for (Root root : userRootList) {
                if(root.getName().equals(requestURI)){
                    isHave = true;
                    break;
                }
            }

            if(isHave){
                return true;
            }
        }

        response.sendRedirect("/error.html");
        return false;
    }
}
